import asyncio
import os
import shutil

from bs4 import BeautifulSoup as bs
from utils.httpClient import HttpClient

HERO_LIST_URL = "https://game.gtimg.cn/images/lol/act/img/js/heroList/hero_list.js"
BASE_IMAGE_PATH = "images/英雄联盟"

HERO_IMAGE_URL = ""

hc = HttpClient()

async def save_hero(parent_path, name, mainImg, **kwargs):
    if not mainImg: return
    image = await hc.get(mainImg, parse_json=False)
    name = name.replace('/', '-')
    with open(f"{parent_path}/{name}.jpg", 'wb') as f:
        f.write(image)


async def fetch_hero(heroId, name, title, **kwargs):
    print(heroId, name, title)
    url = f"https://game.gtimg.cn/images/lol/act/img/js/hero/{heroId}.js"
    data = await hc.get(url)
    skins = data.get("skins")
    parent_path = f"{BASE_IMAGE_PATH}/{name}-{title}"
    if not os.path.exists(parent_path):
        os.makedirs(parent_path)
    for skin in skins:
        await save_hero(parent_path, **skin)


async def main():
    if os.path.exists(BASE_IMAGE_PATH):
        shutil.rmtree(BASE_IMAGE_PATH)
    # 英雄联盟英雄列表
    hero_list = await hc.get(HERO_LIST_URL)
    for hero in hero_list.get('hero'):
        await fetch_hero(**hero)
    await hc.close()

if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())